//
//  TimeAlarmSetViewController.m
//  GKBHouse
//
//  Created by hcy on 14-1-15.
//
//

#import "TimeAlarmSetViewController.h"
#import "Global1.h"
#import "WiringChooseViewController.h"
#import "TimingSetViewController.h"
#import "TimerTableView.h"

@interface TimeAlarmSetViewController ()
{
    MyFormDataRequest *_setTimeRequest;
    IBOutlet UIView *_timeFrameView;

    IBOutlet TimerTableView *_hourTable;
    IBOutlet TimerTableView *_minuteTable;
}
@property (retain, nonatomic)NSArray *weekArray;
@property (retain, nonatomic)UIButton *timeOnBtn;
@property (retain, nonatomic)UIButton *timeOffBtn;
@property (retain, nonatomic)UILabel *wiringsLabel;

@property (retain, nonatomic)NSString *switchIds;

@property (retain, nonatomic)NSMutableDictionary *timingDic;

@property (assign, nonatomic)id target;
@property (assign, nonatomic)SEL action;

@end

@implementation TimeAlarmSetViewController

- (void)dealloc
{
    self.weekArray = nil;
    self.timeOnBtn = nil;
    self.timeOffBtn = nil;
    self.wiringsLabel = nil;
    
    self.switchIds = nil;
    self.timingDic = nil;
    NSLog(@"__dealloc__");
    [super dealloc];
}

- (id)initWithTimingDic:(NSMutableDictionary *)dic saveTarget:(id)target action:(SEL)action
{
    self = [super initWithNibName:@"TimeAlarmSetViewController" bundle:nil];
    if (self) {
        // Custom initialization
        self.timingDic = dic;
        self.target = target;
        self.action = action;
    }
    return self;

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    [self initTopBar];
    [self initView];
    
    [self setViewWithData];
}

- (void)viewDidAppear:(BOOL)animated
{
//    [_hourTable setTableMiddleCellHeightLight];
//    [_minuteTable setTableMiddleCellHeightLight];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
//}


#pragma mark - init

- (void)initTopBar
{
    GKBNavigationBar *topBar = [[GKBNavigationBar alloc]init];
    [topBar setTarget:self returnAction:@selector(goBackAction) withTitle:NSLocalizedString(@"timingSet", nil)];
    [self.view addSubview:topBar];
    [topBar release];
    
}

- (void)dismissView
{
    [self dismissModalViewControllerAnimated:NO];
}

- (void)initView
{
    CGFloat width = DEVICE_HEIGHT - 10.0f*2;
    
    //星期选择
    CGFloat weekX = 10.0f;
    CGFloat weekY = 50.0f;
    CGFloat pWidth = width/7;
    CGFloat pHeight = 30.0f;
    
    
    UIImageView *weekBack = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"weekBack.png"]];
    [weekBack setFrame:CGRectMake(0, weekY - 2, DEVICE_HEIGHT, pHeight + 4)];
    [self.view addSubview:weekBack];
    [weekBack release];
    
    NSMutableArray *weekArray = [NSMutableArray array];
//    NSArray *titleArray = @[@"周一", @"周二", @"周三", @"周四", @"周五", @"周六", @"周日"];
    NSArray *titleArray = @[@"Mon", @"Tue", @"Wed", @"Thurs", @"Friday", @"Sat", @"Sun"];

    UIImage *check = [UIImage imageNamed:@"tCheckOn.png"];//cb_dark_off.png
    UIImage *uncheck = [UIImage imageNamed:@"tCheckOff.png"];//cb_dark_on.png
    
    for (int i = 0; i<7; i++) {
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(weekX, weekY, pWidth, pHeight)];
        btn.tag = i;
        [btn setImage:uncheck forState:UIControlStateNormal];
        [btn setImage:check forState:UIControlStateSelected];
        NSString *title = [titleArray objectAtIndex:i];
        [btn setTitle:NSLocalizedString(title, nil)  forState:UIControlStateNormal];
        [btn.titleLabel setAdjustsFontSizeToFitWidth:YES];
        [btn addTarget:self action:@selector(weekAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        [weekArray addObject:btn];
        [btn release];
        weekX = weekX + pWidth;
    }
    self.weekArray = weekArray;
    
    CGFloat nextY = weekY + pHeight*2;
    //定时开，定时关
    CGFloat timeTypeX = 10.0f;
    CGFloat timeTypeY = nextY;
    CGFloat timeTypeW = 100;
    CGFloat timeTypeH = 40;//pHeight;
    
    UIImage *radioOn = [UIImage imageNamed:@"radioOn.png"];
    UIImage *radioOff = [UIImage imageNamed:@"radioOff.png"];
    UIButton *timingON = [[UIButton alloc]init];
    [timingON setBackgroundImage:[UIImage imageNamed:@"blueNormal.png"] forState:UIControlStateNormal];
    [timingON setBackgroundImage:[UIImage imageNamed:@"blueSelect.png"] forState:UIControlStateHighlighted];
    [timingON setImage:radioOff forState:UIControlStateNormal];
    [timingON setImage:radioOn forState:UIControlStateSelected];
    [timingON setTitle:NSLocalizedString(@"Timing-TimingON", nil) forState:UIControlStateNormal];
    [timingON.titleLabel setAdjustsFontSizeToFitWidth:YES];
    [timingON setFrame:CGRectMake(timeTypeX, timeTypeY, timeTypeW, timeTypeH)];
    timingON.tag = 0;
    [timingON addTarget:self action:@selector(timingTypeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:timingON];
    [timingON release];
    self.timeOnBtn = timingON;
    
    //定时关
    timeTypeY = timeTypeY + timeTypeH + 50;
    UIButton *timingOff = [[UIButton alloc]init];
    [timingOff setBackgroundImage:[UIImage imageNamed:@"redNormal.png"] forState:UIControlStateNormal];
    [timingOff setBackgroundImage:[UIImage imageNamed:@"redSelect.png"] forState:UIControlStateHighlighted];
    [timingOff setImage:radioOff forState:UIControlStateNormal];
    [timingOff setImage:radioOn forState:UIControlStateSelected];
    [timingOff setTitle:NSLocalizedString(@"Timing-TimingOFF", nil) forState:UIControlStateNormal];
    [timingOff.titleLabel setAdjustsFontSizeToFitWidth:YES];
    [timingOff setFrame:CGRectMake(timeTypeX, timeTypeY, timeTypeW, timeTypeH)];
    timingOff.tag = 1;
    [timingOff addTarget:self action:@selector(timingTypeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:timingOff];
    [timingOff release];
    self.timeOffBtn = timingOff;
    
    [self initTimeView];
    [self initWiringsLabel];
    
    
    //电器选择
    CGFloat wiringW = 100;
    CGFloat wiringX = DEVICE_HEIGHT - 10.0f - wiringW;
    CGFloat wiringY = CGRectGetMinY(timingON.frame);
    CGFloat wiringH = 40;
    
    UIButton *wiringBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [wiringBtn setBackgroundImage:[UIImage imageNamed:@"blueNormal.png"] forState:UIControlStateNormal];
    [wiringBtn setBackgroundImage:[UIImage imageNamed:@"blueSelect.png"] forState:UIControlStateHighlighted];
    [wiringBtn addTarget:self action:@selector(wiringAction) forControlEvents:UIControlEventTouchUpInside];
    [wiringBtn setTitle:NSLocalizedString(@"Timing-choose", nil) forState:UIControlStateNormal];
    [wiringBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:17]];
    [wiringBtn.titleLabel setAdjustsFontSizeToFitWidth:YES];
    [wiringBtn setFrame:CGRectMake(wiringX, wiringY, wiringW, wiringH)];
    [self.view addSubview:wiringBtn];
    
    
    //保存
    wiringY = timeTypeY;//DEVICE_WIDTH - 10.0f - wiringH;
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBtn setFrame:CGRectMake(wiringX, wiringY, wiringW, wiringH)];
    [saveBtn setTitle:NSLocalizedString(@"Timing-save", nil) forState:UIControlStateNormal];
    [saveBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:17]];
    [saveBtn setBackgroundImage:[UIImage imageNamed:@"blueNormal.png"] forState:UIControlStateNormal];
    [saveBtn setBackgroundImage:[UIImage imageNamed:@"blueSelect.png"] forState:UIControlStateHighlighted];
    [saveBtn addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveBtn];

}

- (void)initTimeView
{
//    CGRect frame = _timeFrameView.frame;
    
//    CGPoint center = self.view.center;
    
    [_hourTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _hourTable.delegate = self;
    _hourTable.dataSource = self;
    _hourTable.count = 24;
    _hourTable.showsVerticalScrollIndicator = NO;
    [_minuteTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _minuteTable.delegate = self;
    _minuteTable.dataSource = self;
    _minuteTable.count = 60;
    _minuteTable.showsVerticalScrollIndicator = NO;

    CGFloat startY = 50.0f + 30.0f + 20.0f;
    CGFloat startX = (DEVICE_HEIGHT - CGRectGetWidth(_timeFrameView.frame))/2;
    [_timeFrameView setBackgroundColor:[UIColor clearColor]];
    CGRect frame = _timeFrameView.frame;
    frame.origin.x = startX;
    frame.origin.y = startY;
    [_timeFrameView setFrame:frame];
    [self.view addSubview:_timeFrameView];
    
    [_hourTable reloadData];
    [_minuteTable reloadData];
    
}

- (void)initWiringsLabel
{
    CGFloat labelW = 260.0f;//CGRectGetWidth(_timeFrameView.frame);
    CGFloat labelH = 60.0f;
    CGFloat labelX = (CGRectGetWidth(self.view.frame) - labelW)/2;
    CGFloat labelY = CGRectGetMaxY(_timeFrameView.frame) + 2;// DEVICE_WIDTH - 5.0f - labelH;
    
    UILabel *label = [[UILabel alloc]init];
    [label setFrame:CGRectMake(labelX, labelY, labelW, labelH)];
    [label setText:@""];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setNumberOfLines:0];
    [label setFont:[UIFont boldSystemFontOfSize:17]];
    [label setMinimumFontSize:6.0f];
    [label setAdjustsFontSizeToFitWidth:YES];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setTextColor:[UIColor whiteColor]];
    [self.view addSubview:label];
    [label release];
    
    self.wiringsLabel = label;
}

- (void)setViewWithData
{
    //设置星期
    NSString *weekIds = [self.timingDic objectForKey:@"d9_mode"];
    NSArray *days = [weekIds componentsSeparatedByString:@","];
    
    for (NSString *day in days) {
        NSInteger d = day.integerValue;
        
        if (d>0 && d<8) {
            UIButton *weekIndexBtn = [self.weekArray objectAtIndex:d - 1];
            [weekIndexBtn setSelected:YES];
        }
    }
    
    //设置定时开/关
    NSNumber *timingOnOff = [self.timingDic objectForKey:@"d8_orderId"];
    if (timingOnOff.integerValue == 1) {
        self.timeOnBtn.selected = YES;
        self.timeOffBtn.selected = NO;
    }
    if (timingOnOff.integerValue == 2) {
        self.timeOnBtn.selected = NO;
        self.timeOffBtn.selected = YES;
    }
    
    //设置时间
    NSNumber *hour = [self.timingDic objectForKey:@"d10_time1"];
    NSNumber *minute = [self.timingDic objectForKey:@"d11_time2"];
    
    [_hourTable start:hour.integerValue];
    [_minuteTable start:minute.integerValue];
   
    
    NSString *switchStr = [self.timingDic objectForKey:@"switchStr"];
    NSString *switchNames = [TimingSetViewController wirings:switchStr];
    self.wiringsLabel.text = switchNames;

   
}

#pragma mark - action

- (void)weekAction:(id)sender
{
    UIButton *btn = sender;
    
    btn.selected = !btn.selected;

}

- (void)timingTypeAction:(id)sender
{
    UIButton *btn = sender;
    
    if (btn.selected) {
        return;
    }
    
    btn.selected = !btn.selected;
    
    if (self.timeOnBtn == btn) {
        self.timeOffBtn.selected = NO;
    }
    
    if (self.timeOffBtn == btn) {
        self.timeOnBtn.selected = NO;
    }
    
}

- (IBAction)hourAddAction
{
    [_hourTable addOne];
}

- (IBAction)hourCutAction
{
    [_hourTable cutOne];
}

- (IBAction)minuteAddAction
{
    [_minuteTable addOne];
}

- (IBAction)minuteCutAction
{
    [_minuteTable cutOne];
}

- (void)wiringAction
{
    WiringChooseViewController *wiring = [[WiringChooseViewController alloc]initWithTimingDic:self.timingDic saveTarget:self action:@selector(wiringChooseChangeAction)];
    [self presentModalViewController:wiring animated:NO];
    [wiring release];
}

- (void)saveAction
{
//    [self saveSuccess];
//    return;//test
    
//    BOOL weekSelectedFlag = NO;
//    for (UIButton *btn in self.weekArray) {
//        if (btn.selected) {
//            weekSelectedFlag = YES;
//            break;
//        }
//    }
//    
//    if (weekSelectedFlag == NO) {//未设置日期
//        
//        NSString *tip = NSLocalizedString(@"Timing-set-no-date", nil);;
//        [iToast showTip:tip gravity:iToastGravityBottom];
//        
//        return;
//    }
    
    //未设置开关状态
    if (!self.timeOnBtn.selected && !self.timeOffBtn.selected) {
        
        NSString *tip = NSLocalizedString(@"Timing-set-no-switch", nil);;
        [iToast showTip:tip gravity:iToastGravityBottom];
        
        return;
    }
    
    //未选择电器
    if ([[self.timingDic objectForKey:@"switchStr"] length] == 0) {
        
        NSString *tip = NSLocalizedString(@"Timing-set-no-wiring", nil);;
        [iToast showTip:tip gravity:iToastGravityBottom];
        
        return;
    }
    
    [self setTime];
}


- (void)goBackAction
{
    if (_setTimeRequest) {
        [WebServices removeRequest:_setTimeRequest];
    }

    [self dismissView];
}

- (void)saveSuccess
{
    NSInteger timingOnOffFlag = 2;//关
    if (self.timeOnBtn.selected) {
        timingOnOffFlag = 1;
    }
    
    //提交设置定时成功后， 默认是启动状态：1
    [self.timingDic setObject:[NSNumber numberWithInteger:1] forKey:@"time_state"];
    
    [self.timingDic setObject:[NSNumber numberWithInteger:timingOnOffFlag] forKey:@"d8_orderId"];
    
    NSInteger hourRow = _hourTable.currentIndex;
    NSInteger minuteRow = _minuteTable.currentIndex;

    [self.timingDic setObject:[NSNumber numberWithInteger:hourRow] forKey:@"d10_time1"];
    [self.timingDic setObject:[NSNumber numberWithInteger:minuteRow] forKey:@"d11_time2"];
    
    
    NSMutableArray *weekArray = [NSMutableArray array];
    
    for (int i = 0; i < 7; i++) {
        
        UIButton *btn = [self.weekArray objectAtIndex:i];
        
        if (btn.selected) {
            NSString *index = [NSString stringWithFormat:@"%d", i+1];
            [weekArray addObject:index];
        }
    }
    NSString *weekStr = @"";
    if ([weekArray count]>0) {
        weekStr = [weekArray componentsJoinedByString:@","];
    }
    else{//未选择周，则设置”0“表示一次
        weekStr = @"0";
    }
    
    [self.timingDic setObject:weekStr forKey:@"d9_mode"];
    
//    [self.timingDic setObject:self.switchIds forKey:@"switchStr"];
    

    if(self.target && self.action)
    {
        [self.target performSelector:self.action];
    }
    
    [self dismissView];

}

- (void)wiringChooseChangeAction
{
    NSString *switchStr = [self.timingDic objectForKey:@"switchStr"];
    NSString *switchNames = [TimingSetViewController wirings:switchStr];
    self.wiringsLabel.text = switchNames;
}

#pragma mark - 时间控制

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kTimerTableViewCellHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    TimerTableView *table = (TimerTableView *)tableView;
    
    return table.count*2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        [cell.textLabel setFrame:CGRectMake(0, 0, tableView.frame.size.width, kTimerTableViewCellHeight)];
        [cell.textLabel setTextAlignment:NSTextAlignmentCenter];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.backgroundColor=[UIColor clearColor];
    }
    
    [cell.textLabel setTextColor:kNotSelectColor];
    
    TimerTableView *table = (TimerTableView *)tableView;
    
    NSString *hour = [[NSString alloc]initWithFormat:@"%02d", (indexPath.row + table.count/2)%table.count];
    cell.textLabel.text = hour;
    cell.textLabel.font = [UIFont systemFontOfSize:13];
    return cell;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
    if(!decelerate)
    {
        //        NSLog(@"OK,真正停止了，do something");//
        NSLog(@"___手动停止");//
        [(TimerTableView *)scrollView adjustTableCenterAlign];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"___划动停止");//
    [(TimerTableView *)scrollView adjustTableCenterAlign];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [(TimerTableView *)scrollView setTableCircle];
}


#pragma mark - UITextFieldDelegate

- (BOOL)isDigit:(NSString *)text
{
    NSPredicate *prd = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"^[0-9]*$"];
    return [prd evaluateWithObject:text];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"%f,%f",self.view.center.x, self.view.center.y);
    CGPoint center = [UIApplication sharedApplication].keyWindow.center;
    center.x = center.x + 70;
    self.view.center = center;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *result = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    BOOL isDigit = [self isDigit:result];
    
    if (!isDigit) {
        return NO;
    }
    
    NSInteger length = [result length];
    
    
    if (length > 0) {
        
//        NSInteger inputPage = result.integerValue;
//        
//        if (textField == _hourField) {
//            if (inputPage < 0 || inputPage > 23) {
//                return NO;
//            }
//        }
//        if (textField == _minuteField) {
//            if (inputPage < 0 || inputPage > 59) {
//                return NO;
//            }
//        }
        
    }
    
    if (length > 2) {
        return NO;
    }
    
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSString *str = textField.text;
    
    NSString *result = [NSString stringWithFormat:@"%02d", str.integerValue];
    textField.text = result;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    CGPoint center = [UIApplication sharedApplication].keyWindow.center;
    self.view.center = center;
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    CGPoint center = [UIApplication sharedApplication].keyWindow.center;
    self.view.center = center;
}

#pragma mark - 网络操作

- (NSString *)setTimeBody
{
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\",\"groupNum\":\"%@\",\"hour\":\"%@\",\"minute\":\"%@\",\"switchId\":\"%@\",\"ctlId\":\"%@\",\"timeMode\":\"%@\"}]";
    
    ;
    NSString *groupNum = @"";
    NSString *hour = @"";
    NSString *minute = @"";
    NSString *switchId = @"";
    NSString *ctlId = @"";
    NSString *timeMode = @"";
    
    groupNum = [self.timingDic objectForKey:@"groupNo"];
    
    NSInteger hourRow = _hourTable.currentIndex;
    NSInteger minuteRow = _minuteTable.currentIndex;
    
    hour = [NSString stringWithFormat:@"%d", hourRow];
    minute = [NSString stringWithFormat:@"%d", minuteRow];
    switchId = [self.timingDic objectForKey:@"switchStr"];
    
    if (self.timeOnBtn.selected) {
        ctlId = @"1";
    }
    if (self.timeOffBtn.selected) {
        ctlId = @"2";
    }
    
    long int mode = 0;
    
    for (int i = 0; i < 7; i++) {
        
        UIButton *btn = [self.weekArray objectAtIndex:i];
        
        if (btn.selected) {
            mode = mode + powl(10, i);
        }
    }
    
    timeMode = [NSString stringWithFormat:@"%ld", mode];
    
    NSString *body = [NSString stringWithFormat:fomat, sessionId, groupNum, hour, minute, switchId, ctlId, timeMode];
    
    return body;
}

- (void)setTime
{
    NSString *body = [self setTimeBody];
    
    NSString *tip = NSLocalizedString(@"Timing-saving", nil);;
    
    [iToast showTip:tip gravity:iToastGravityBottom];
    
    NSString *errorTip = NSLocalizedString(@"operatFailure", nil);
    _setTimeRequest = [WebServices requestStartOrder:@"setTime" body:body target:self action:@selector(setTimeEnd:) errorTip:errorTip];
    
}

- (void)setTimeEnd:(NSDictionary *)dic
{
    [WebServices setShowConnectting:NO];//关闭提示
    
    NSNumber *result = [dic objectForKey:@"result"];
    
    if (result.integerValue == 0 && result != nil) {
        NSString *tip = NSLocalizedString(@"operat success!", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];
        
        [self saveSuccess];
    }
    else
    {
        NSString *tip = NSLocalizedString(@"operatFailure", nil);
        [iToast showTip:tip gravity:iToastGravityBottom];
    }
}
@end
